package com.bw.educate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.educate.common.ResponseResult;
import com.bw.educate.common.auth.UserInfo;
import com.bw.educate.common.utils.MD5Util;
import com.bw.educate.entity.EduUser;
import com.bw.educate.mapper.EduUserMapper;
import com.bw.educate.service.IEduUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-12
 */
@Service
public class EduUserServiceImpl extends ServiceImpl<EduUserMapper, EduUser> implements IEduUserService {


    @Autowired
    private EduUserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public ResponseResult getList(int currentPage, int pageSize, EduUser user) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(currentPage,pageSize);
            QueryWrapper queryWrapper = new QueryWrapper();
            if(user.getShowName()!=null){
                queryWrapper.like("SHOW_NAME",user.getShowName());
            }
            queryWrapper.eq("STATUS",0);
            queryWrapper.or();
            queryWrapper.eq("STATUS",1);
            List list = userMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setResult(pageInfo);
        }catch (Exception e){

            result.setSuccess(false);
            result.setMessage("学生列表查询失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult addStudent(EduUser user) {
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            MD5Util.md5Encrypt32Lower(MD5Util.md5Encrypt32Lower(user.getLoginPwd()));
            user.setCreateTime(new Date());
            user.setStatus((long) 0);
            user.setIsAvalible((long) 1);

            userMapper.insert(user);
            result.setMessage("保存成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("学员保存失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult freezeStudnet(Long id) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            EduUser eduUser = userMapper.selectById(id);
            eduUser.setStatus((long) 1);
            eduUser.setIsAvalible((long) 2);
            userMapper.updateById(eduUser);
            result.setMessage("冻结成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("学员冻结失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult delStudnet(Long id) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            EduUser eduUser = userMapper.selectById(id);
            eduUser.setStatus((long) 2);
            userMapper.updateById(eduUser);
            result.setMessage("删除成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("学员删除失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult findStudent(Long id) {

        ResponseResult result=ResponseResult.SUCCESS();

        try {
            result.setResult(userMapper.selectById(id));
            result.setMessage("查询成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("学员查询失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult userService(EduUser user) {

        ResponseResult result=ResponseResult.SUCCESS();

        try {
            userMapper.updateById(user);
            result.setMessage("修改成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("学员修改失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult updateisAvalible(long id, long isAvalible) {
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            EduUser eduUser = userMapper.selectById(id);
            if(eduUser.getIsAvalible()==1){
                eduUser.setStatus((long) 1);
                eduUser.setIsAvalible((long) 2);
                userMapper.updateById(eduUser);
                result.setMessage("冻结成功");
            }else{
                eduUser.setStatus((long) 0);
                eduUser.setIsAvalible((long) 1);
                userMapper.updateById(eduUser);
                result.setMessage("启用成功");
            }

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("操作失败"+e.toString());
        }
        return result;
    }


    @Override
    public ResponseResult login(EduUser user, HttpServletResponse response) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("LOGIN_NAME", user.getLoginName());//用登录名或者email登录
//            queryWrapper.or();
//            queryWrapper.eq("EMAIL",user.getLoginName());

            String md5 = MD5Util.md5Encrypt32Lower(user.getLoginPwd());
            queryWrapper.eq("LOGIN_PWD",md5);//验证密码
            queryWrapper.eq("STATUS",0);
            queryWrapper.eq("IS_AVALIBLE",1);
            List<EduUser> list = userMapper.selectList(queryWrapper);
            if (list==null || list.size()==0){//登录不正确
                result.setSuccess(false);
                result.setMessage("登陆失败，用户名或密码不正确！！！");
                return result;
            }

            EduUser eduUser = list.get(0);
            //随机生成一个token，存储到浏览器的cookie中，同时token存储到redis当中【cookie+redis实现了登录】
            UserInfo userInfo = new UserInfo(eduUser.getId(),eduUser.getLoginName());
            String token = UUID.randomUUID().toString();//生成随机token
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(1800);//超时时间  设置最长时间--秒
            cookie.setPath("/");
            response.addCookie(cookie);

            //将用户信息存储到redis中
            redisTemplate.opsForValue().set(token,userInfo);
            redisTemplate.expire(token,30, TimeUnit.MINUTES);

            Map map = new HashMap();
            map.put("user",list.get(0));
            map.put("token",token);

            result.setMessage("登陆成功！！！");
            result.setResult(map);
        }catch (Exception e){

            result.setSuccess(false);
            result.setMessage("登陆失败"+e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult registerLogin(EduUser user) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            if (user.getMobile()==null || user.getLoginName()==null || user.getLoginPwd()==null){
                result.setSuccess(false);
                result.setMessage("请将信息输入完整在进行注册");
                return result;
            }
            if (user.getShowName()==null || user.getSex()==null || user.getAge()==null){
                result.setSuccess(false);
                result.setMessage("请将信息输入完整在进行注册");
                return result;
            }
            if (user.getEmail()==null){
                result.setSuccess(false);
                result.setMessage("请将信息输入完整在进行注册");
                return result;
            }

            String pwd = MD5Util.md5Encrypt32Lower(MD5Util.md5Encrypt32Lower(user.getLoginPwd()));
            user.setLoginPwd(pwd);
            user.setCreateTime(new Date());
            user.setStatus((long) 0);
            user.setIsAvalible((long) 1);

            userMapper.insert(user);
            result.setMessage("注册成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("学员保存失败"+e.toString());
        }
        return result;
    }


}
